package org.elsa.fingobtb.service.impl

import com.alibaba.fastjson.JSON
import org.elsa.fingobtb.api.response.BaseResult
import org.elsa.fingobtb.api.response.GeneralResult
import org.elsa.fingobtb.common.func.BtbRestfulOption
import org.elsa.fingobtb.entity.response.BookData
import org.elsa.fingobtb.entity.response.RmbPrice
import org.elsa.fingobtb.service.Buy
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DecimalFormat

/**
 * @author valord577
 * @date 2018/7/19 17:53
 */
@Service
class BuyImpl : Buy {

    private val decimalFormat = DecimalFormat("0")

    private val logger = LoggerFactory.getLogger(BuyImpl::class.java)

    override fun buyLimit(symbol: String, price: Int): BaseResult {

        // 获取RMB对应的价格
        val rmbPrice = JSON.parseObject(BtbRestfulOption.getRmbPrice(), RmbPrice::class.java)
        val dataList = JSON.parseArray(JSON.toJSONString(rmbPrice.data), RmbPrice.RmbPriceData::class.java)

        var ethData: RmbPrice.RmbPriceData? = null
        when (dataList[2].symbol) {
            "eth" -> ethData = dataList[2]

            else -> {
                for (l in dataList) {
                    if ("eth" == l.symbol) {
                        ethData = l
                    }
                }
            }
        }

        if (null == ethData) {
            return BaseResult(false, "找不到中间计价币")
        }

        logger.info(ethData.toString())

        // 用美元换算eth 并舍弃最后一位小数
        var ethAmount = price / 100 / ethData.lastPrice
        decimalFormat.roundingMode = RoundingMode.DOWN
        ethAmount = decimalFormat.format(ethAmount * 10E15).toDouble() / 10E15
        logger.info("客户输入的金额可以换算的eth个数为: {}", ethAmount)

        if (0.00 == ethAmount) {
            return BaseResult(false, "输入的金额不足以兑换计价币")
        }

        // 获取交易深度 买一价 行情
        val bookData = JSON.parseObject(BtbRestfulOption.getBook("${symbol}_eth"), BookData::class.java)
//        val cheapestPrice = bookData.asks[bookData.asks.size - 1][0]
        val cheapestPrice = 0.00000350
        logger.info("当前卖的最便宜的价格(卖一价): {}", cheapestPrice)
        val amount = ethAmount / cheapestPrice.toDouble()
        logger.info("当前用户按照卖一价最多可以买: {}个", amount*0.95)
        val dealAmount: String
        val bigDecimal = BigDecimal(amount*0.95).toInt()
        dealAmount = bigDecimal.toString()
        logger.info("交易成功 成功购买{}个", dealAmount)
        return GeneralResult<String>(true, "交易成功 成功购买${dealAmount}个", dealAmount)

        // 下单 调用btb接口
        /*val response = BtbRestfulOption.buy("${symbol}_eth", cheapestPrice, amount.toString())
        logger.info("下单操作 btb返回: $response")

        try {
            val result = JSON.parseObject(response, OrderResult.Success::class.java)
            // 查询订单 获取订单状态
            val orderInfo = JSON.parseObject(BtbRestfulOption.getOrderInfo("${symbol}_eth", result.order_id.toLong()), OrderDetail::class.java)

            if ("true" != orderInfo.result) {
                logger.info("查询过快 暂未找到订单")
                return BaseResult(false, "查询过快 暂未找到订单")
            }

            val order = JSON.parseArray(JSON.toJSONString(orderInfo.orders), OrderDetail.Order::class.java)

            // bigDecimal 消耗太多性能 做个if处理
            val dealAmount: String
            if (StringUtils.contains(order[0].deal_amount, "E")) {
                val bigDecimal = BigDecimal(order[0].deal_amount)
                dealAmount = bigDecimal.toPlainString()
            } else {
                dealAmount = order[0].deal_amount
            }
            logger.info("交易成功 成功购买{}个", dealAmount)
            return GeneralResult<String>(true, "交易成功 成功购买${dealAmount}个", dealAmount)

        } catch (e: Exception) {
            // 下单失败
            val result = JSON.parseObject(response, OrderResult.Error::class.java)
            if (1002 == result.error_code) {
                val fundsData = JSON.parseObject(BtbRestfulOption.getFunds(), FundsData::class.java)
                val info = JSON.parseObject(JSON.toJSONString(fundsData.info), FundsData.Info::class.java)
                val funds = JSON.parseObject(JSON.toJSONString(info.funds), FundsData.Info.Founds::class.java)
                val free = JSON.parseObject(JSON.toJSONString(funds.free), FundsData.Info.Founds.Free::class.java)
                SmsApi.send("客户下单时, btb交易额大于余额, ETH余额为${free.eth} " + "【芬果财经】", Account.tipMobile)
                return BaseResult(false, "交易失败 交易额大于余额")
            }
            logger.error("交易失败: ${e.message}")
            return BaseResult(false, "交易失败 btb返回: $response")
        }*/



    }
}